import React from 'react';
import { api } from 'js/api/api';
import './playerSelect.scss';
import { userData } from 'js/core/userData';
import { Link, browserHistory } from 'react-router';

class PlayerSelect extends React.Component {
    constructor() {
        super()
        let data = [];
        this.state = {
            type: 1,
            data: data,
            selectValue: null,
        }
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                LoginApi.createPlayer({ name: values.name }, (err, data) => {
                    if (err === 0) {
                        this.getPlayerList();
                    }
                });
            }
        });
    }
    componentDidMount = () => {
        this.getPlayerList();
    }
    getPlayerList = () => {
        api('getPlayerList', (err, data) => {
            if (err === 0) {
                if (data.length === 0) {
                    browserHistory.push('/createPlayer');
                } else {
                    this.setState({ selectValue: data[0].id, data: data })
                }

            }
        });
    }
    playerLogin = () => {
        api('selectPlayer', { id: this.state.selectValue }, (err, data) => {
            if (err === 0) {
                userData.set('player', data);
                browserHistory.push('/map');
            }
        });
    }
    select = (index) => {
        this.setState({ selectValue: index })
    }
    render() {
        let node;
        node = this.state.data.map((item, i) => {
            let selectClass = '';
            if (this.state.selectValue === item._id) {
                selectClass = 'active';
            }
            return <div className={"item " + selectClass} key={item._id} onClick={this.select.bind(this, item._id)}>{item.player.name}</div>
        });
        return <div id="playerSelect">
            <div className="flex">
                <div className="info flex-col-7">
                    <div className="content"></div>
                    <button onClick={this.playerLogin}>开始</button>
                </div>
                <div className="select flex-g-1">
                    <div className="itemList">{node}</div>
                </div>
            </div>
            <Link to="createPlayer" className="create">新的冒险</Link>
        </div >
    }
}



export default PlayerSelect;